package com.semp.jadoma.admin.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;

import com.semp.jadoma.admin.form.DogModifyForm;
import com.semp.jadoma.admin.utils.Config;
import com.semp.jadoma.admin.utils.webapp.Forward;
import com.semp.jadoma.admin.utils.webapp.Session;
import com.semp.jadoma.core.model.Dog;
import com.semp.jadoma.core.service.DogService;

public class DogModifyAction extends RootAction {

	private final static Logger logger = Logger.getLogger(DogModifyAction.class);
	
	@Override
	public String executeChild(ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		DogModifyForm dogModifyForm = (DogModifyForm) form;
		switch (dogModifyForm.getStep()) {
		/*
		 * Display page
		 */
		case DogModifyForm.STEP_DISPLAY_SEARCH:
			return Forward.SEARCH;
		/*
		 * Search dog like name
		 */
		case DogModifyForm.STEP_SEARCH:
			String searchedName = dogModifyForm.getSearchName();
			List dogList = DogService.getInstance().findDogLikeName(searchedName);
			request.setAttribute(Session.LIST_BEAN_DOG, dogList);
			return Forward.SEARCH;
		case DogModifyForm.STEP_DISPLAY_MODIF:
			long dogId = dogModifyForm.getId();
			Dog dog = DogService.getInstance().findDog(dogId);
			request.setAttribute(Session.BEAN_DOG, dog);
			return Forward.MODIFY;
		case DogModifyForm.STEP_MODIF:
			long dogId2 = dogModifyForm.getId();
			Dog dog2 = DogService.getInstance().findDog(dogId2);
			//dog.setBreedingId(breedingId);
			dog2.setColor(dogModifyForm.getColor());
			dog2.setPeel(dogModifyForm.getPeel());
			dog2.setName(dogModifyForm.getName());
			dog2.setNickName(dogModifyForm.getNickName());
			//dog.setSaleInfos(saleInfos);
			dog2.setSize(dogModifyForm.getSize());
			dog2.setWeight(dogModifyForm.getWeight());
			dog2.setSex(dogModifyForm.getSex());
			String dateAsString = dogModifyForm.getBirthDay();
			Date birthDay;
			try {
				birthDay = Config.DATE_FORMAT_J.parse(dateAsString);
			} catch (RuntimeException e) {
				logger.error("Wrong date format", e);
				birthDay = new Date();
			}
			dog2.setBirthDay(birthDay);
			DogService.getInstance().updateDog(dog2);
			logger.info("Dog: " + dogModifyForm.getName() + " modified");
			request.setAttribute(Session.BEAN_DOG, dog2);
			return Forward.SUCCESS;
		}
		return Forward.FAILURE;
	}

}
